package com.itheima.service.impl;


import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.itheima.entity.Employee;
import com.itheima.mapper.EmployeeDAO;
import com.itheima.service.EmployeeService;
import com.itheima.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 *员工模块业务层实现类
 * @author msi
 * @date 2022/5/17
 * @version 1.0
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Resource
    private EmployeeDAO dao;

    @Override
    public Employee getUser(Long id) {
        Employee employee = dao.selectById(id);

        return employee;

    }

    /**
     * 新增
     *
     * @param employee
     * @return
     */
    @Override
    public Boolean insertUser(Employee employee) {
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        String name = employee.getUsername();
        qw.eq("username", name);
        Employee userByUsername = dao.selectOne(qw);

        MD5 md5 = MD5.create();
        String password = md5.digestHex(name);
        employee.setPassword(password);
        long user = 1L;
        employee.setCreateUser(user);
        employee.setUpdateUser(user);

        if (userByUsername == null) {
            dao.insert(employee);
            return true;
        }


        return false;
    }

    @Override
    public Boolean updateUser(Employee employee) {
        int i = dao.updateById(employee);
        return i > 0;
    }

    @Override
    public ResultVO listLimit(String name, long page, long size) {

        IPage<Employee> page1 = new Page<>(page, size);
        dao.selectPage(page1, null);
        List<Employee> records = page1.getRecords();
        long pages = page1.getPages();

        ResultVO resultVO = new ResultVO();
        resultVO.setPages(pages);
        resultVO.setCurrent(page);
        resultVO.setSize(size);
        resultVO.setHitCount(false);
        resultVO.setRecords(records);
        resultVO.setTotal(page1.getTotal());

        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);

        if (name != null) {
            dao.selectPage(page1, queryWrapper);
            resultVO.setRecords(page1.getRecords());
            resultVO.setTotal(page1.getTotal());
        }


        return resultVO;
    }


    @Override
    public Employee getLoginResult(String username) {

        QueryWrapper<Employee> qw = new QueryWrapper<>();
        qw.eq("username", username);

        Employee employee = dao.selectOne(qw);

        return employee;
    }
}
